from fastapi import Request, APIRouter
from fastapi.responses import Response, StreamingResponse
from services.storage import BaseStorage, LocalStorageURLCoder

router = APIRouter()


# 本地存储时的url解析入口
@router.get("/{code}")
async def ossTransport(code: str, request: Request) -> Response:
    storage: BaseStorage = request.app.state.storage
    # 只适于: LocalStorageURLCoder
    if not isinstance(storage, LocalStorageURLCoder):
        return Response("not find", status_code=404)

    localFilePath = storage.decode(code)

    def iterfile():  # (1)
        with open(localFilePath, mode="rb") as file_like:  # (2)
            yield from file_like  # (3)

    return StreamingResponse(iterfile(), media_type="audio/wav")
